
# coding=utf-8
import traceback
from time import sleep

import pymysql
import requests
from Common.CusMethod import random_str, random_letter, random_code, get_data_time, get_data
from Common.FontColor import outcome
from Common.ReExecution import NumberCycles
from Common.ReadWriteIni import ReadWrite
from Common.ReadYaml import ReadPublic, ConfigYaml, ReadKeyWorld
from Common.Login import Login
from random import choice

"""
待检核工作台
"""

class BacklogData:
    def __init__(self):
        """
        关于产品模块相关公共数据类接口数据
        """
        self.login = Login
        self.token_key = ConfigYaml('token_key').base_config
        self.token_value = ReadWrite().read_ini_token()
        self.headers = {self.login.content_type_key: self.login.content_json_type_value,
                        self.token_key: self.token_value}

        self.warehouse_name = ConfigYaml('wawarehouse_name').base_config
        self.matching_world = ConfigYaml('matching_world').base_config
        self.channle_name = ConfigYaml('channle_name').base_config
        self.base_url = ConfigYaml('domain_name').base_url
        self.login_job_url = ConfigYaml('job-manager').base_url
        self.dir = "backlog"
        self.key_world = ReadKeyWorld(catalog="backlog")
        self.host = ReadKeyWorld(catalog=self.dir).key_world_value("host")
        self.port = ReadKeyWorld(catalog=self.dir).key_world_value("port")
        self.user = ReadKeyWorld(catalog=self.dir).key_world_value("user")
        self.passwd = ReadKeyWorld(catalog=self.dir).key_world_value("passwd")
        self.db = ReadKeyWorld(catalog=self.dir).key_world_value("db")

    def job_to_review(self):
        """
            1.依赖所有的备货参数用例执行完成后
            2.测试待检核的用例之前线执行job
        """
        self.del_order()
        self.del_virtual_order()
        self.del_virtual_order_line_item()
        self.del_supplier()
        self.del_inventory()
        self.del_supplier_sku_relation()
        self.del_sku_purchaser_reserve_days_relation()
        self.del_sku_intransit()
        self.insert_order()
        self.insert_virtual_order()
        self.insert_virtual_order_line_item()
        self.insert_supplier()
        self.insert_inventory()
        self.insert_supplier_sku_relation()
        # self.insert_sku_purchaser_reserve_days_relation()
        self.insert_sku_intransit()
        self.update_order()
        job_list = ReadKeyWorld(catalog=self.dir).key_world_value("job_id")
        # 遍历jobid执行定时任务，在执行任务前执行sql
        for id in job_list:
            jobid = id
            r = self.job_to_requisition_review(jobid)
            sleep(1)
            print(r)




    def job_manager_login(self):
        """登录定时任务"""
        public_data = ReadPublic(catalog=self.dir, key='job_manager_login')
        url = self.login_job_url + public_data.public_value("url")
        #data = public_data.public_value("bar")
        r = requests.post(url, stream=True, verify=False)
        cookies = r.cookies
        cookie = requests.utils.dict_from_cookiejar(cookies)
        return cookie

    def job_to_requisition_review(self, jobid=''):
        """
        启动需求计算任务，将备货参数列表数据同步至检核工作台（待检核列表）
        jobid: 18	清洗订单信息任务
            19  计算销量任务
            20  计算未发货量任务
            21  需求检核工作台（待检核-->超时未处理）
            22  需求检核工作台（已检核-->采购需求）
            23. 启动需求计算任务(qa环境23， beta环境25）
        """
        # job_list = ReadKeyWorld(catalog=self.dir).key_world_value("job_id")
        cookie = self.job_manager_login()
        id = jobid
        public_data = ReadPublic(catalog=self.dir, key="job_to_requisition_review")
        url = self.login_job_url + public_data.public_value("url")
        data = public_data.public_value("bar")
        data['id'] = id
        r = requests.post(url, cookies=cookie, params=data, stream=True, verify=False)
        return r


    def del_order(self):
        """清空订单表数据"""
        public_data = ReadPublic(catalog=self.dir, key="sql")
        del_order = public_data.public_value('del_order')
        try:
            conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db)
            cur = conn.cursor()
            cur.execute(del_order)
            print("清空订单表（order）数据成功")
            # return True
        except:
            self.singular = str(traceback.format_exc())
            outcome('red', self.singular)
            return self.singular
        finally:
            cur.close()
            conn.commit()
            conn.close()

    def del_virtual_order(self):
        """清空虚拟订单表数据"""
        public_data = ReadPublic(catalog=self.dir, key="sql")
        del_virtual_order = public_data.public_value('del_virtual_order')
        try:
            conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db)
            cur = conn.cursor()
            cur.execute(del_virtual_order)
            print("清空虚拟订单表（virtual_order）数据成功")
        except:
            self.singular = str(traceback.format_exc())
            outcome('red', self.singular)
            return self.singular
        finally:
            cur.close()
            conn.commit()
            conn.close()

    def del_virtual_order_line_item(self):
        """清空虚拟订单条目"""
        public_data = ReadPublic(catalog=self.dir, key="sql")
        del_virtual_order_line_item = public_data.public_value('del_virtual_order_line_item')
        try:
            conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db)
            cur = conn.cursor()
            cur.execute(del_virtual_order_line_item)
            print("清空虚拟订单条目表（virtual_order_line_item）数据成功")
        except:
            self.singular = str(traceback.format_exc())
            outcome('red', self.singular)
            return self.singular
        finally:
            cur.close()
            conn.commit()
            conn.close()

    def del_supplier(self):
        """清空供应商"""
        public_data = ReadPublic(catalog=self.dir, key="sql")
        del_supplier = public_data.public_value('del_supplier')
        try:
            conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db)
            cur = conn.cursor()
            cur.execute(del_supplier)
            print("清空供应商表（supplier）数据成功")
        except:
            self.singular = str(traceback.format_exc())
            outcome('red', self.singular)
            return self.singular
        finally:
            cur.close()
            conn.commit()
            conn.close()


    def del_inventory(self):
        """清空库存信息"""
        public_data = ReadPublic(catalog=self.dir, key="sql")
        del_inventory = public_data.public_value('del_inventory')
        try:
            conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db)
            cur = conn.cursor()
            cur.execute(del_inventory)
            print("清空库存信息表（inventory）数据成功")
        except:
            self.singular = str(traceback.format_exc())
            outcome('red', self.singular)
            return self.singular
        finally:
            cur.close()
            conn.commit()
            conn.close()

    def del_supplier_sku_relation(self):
        """清空供应商和sku关系"""
        public_data = ReadPublic(catalog=self.dir, key="sql")
        del_supplier_sku_relation = public_data.public_value('del_supplier_sku_relation')
        try:
            conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db)
            cur = conn.cursor()
            cur.execute(del_supplier_sku_relation)
            print("清空供应商和sku关系表（supplier_sku_relation）数据成功")
        except:
            self.singular = str(traceback.format_exc())
            outcome('red', self.singular)
            return self.singular
        finally:
            cur.close()
            conn.commit()
            conn.close()

    def del_sku_purchaser_reserve_days_relation(self):
        """清空sku与采购员 备货天数关系表"""
        public_data = ReadPublic(catalog=self.dir, key="sql")
        del_sku_purchaser_reserve_days_relation = public_data.public_value('del_sku_purchaser_reserve_days_relation')
        try:
            conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db)
            cur = conn.cursor()
            cur.execute(del_sku_purchaser_reserve_days_relation)
            print("清空sku与采购员 备货天数关系表（sku_purchaser_reserve_days_relation）数据成功")
        except:
            self.singular = str(traceback.format_exc())
            outcome('red', self.singular)
            return self.singular
        finally:
            cur.close()
            conn.commit()
            conn.close()

    def del_sku_intransit(self):
        """清空在途表数据"""
        public_data = ReadPublic(catalog=self.dir, key="sql")
        del_sku_intransit = public_data.public_value('del_sku_intransit')
        try:
            conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db)
            cur = conn.cursor()
            cur.execute(del_sku_intransit)
            print("清空在途表数据表（sku_intransit）数据成功")
        except:
            self.singular = str(traceback.format_exc())
            outcome('red', self.singular)
            return self.singular
        finally:
            cur.close()
            conn.commit()
            conn.close()

    def insert_order(self):
        """向订单表插入数据库"""
        public_data = ReadPublic(catalog=self.dir, key="sql")
        insert_order = public_data.public_value('insert_order')
        try:
            conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db)
            cur = conn.cursor()
            cur.execute(insert_order)
            print("订单表（order）插入数据成功")
        except:
            self.singular = str(traceback.format_exc())
            outcome('red', self.singular)
            return self.singular
        finally:
            cur.close()
            conn.commit()
            conn.close()

    def insert_virtual_order(self):
        """向虚拟订单表插入数据"""
        public_data = ReadPublic(catalog=self.dir, key="sql")
        insert_virtual_order = public_data.public_value('insert_virtual_order')
        try:
            conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db)
            cur = conn.cursor()
            cur.execute(insert_virtual_order)
            print("虚拟订单表（virtual_order）插入数据成功")
        except:
            self.singular = str(traceback.format_exc())
            outcome('red', self.singular)
            return self.singular
        finally:
            cur.close()
            conn.commit()
            conn.close()

    def insert_virtual_order_line_item(self):
        """向空虚拟订单条目表插入数据"""
        public_data = ReadPublic(catalog=self.dir, key="sql")
        insert_virtual_order_line_item = public_data.public_value('insert_virtual_order_line_item')
        try:
            conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db)
            cur = conn.cursor()
            cur.execute(insert_virtual_order_line_item)
            print("空虚拟订单条目表（virtual_order_line_item）插入数据成功")
        except:
            self.singular = str(traceback.format_exc())
            outcome('red', self.singular)
            return self.singular
        finally:
            cur.close()
            conn.commit()
            conn.close()

    def insert_supplier(self):
        """向supplier表插入供应商信息"""
        public_data = ReadPublic(catalog=self.dir, key="sql")
        insert_supplier = public_data.public_value('insert_supplier')
        try:
            conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db)
            cur = conn.cursor()
            cur.execute(insert_supplier)
            print("供应商表（supplier）插入数据成功")
        except:
            self.singular = str(traceback.format_exc())
            outcome('red', self.singular)
            return self.singular
        finally:
            cur.close()
            conn.commit()
            conn.close()

    def insert_inventory(self):
        """向inventory库存表插入数据"""
        public_data = ReadPublic(catalog=self.dir, key="sql")
        insert_inventory = public_data.public_value('insert_inventory')
        try:
            conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db)
            cur = conn.cursor()
            cur.execute(insert_inventory)
            print("库存表（inventory）插入数据成功")
        except:
            self.singular = str(traceback.format_exc())
            outcome('red', self.singular)
            return self.singular
        finally:
            cur.close()
            conn.commit()
            conn.close()

    def insert_supplier_sku_relation(self):
        """向供货关系表插入数据"""
        public_data = ReadPublic(catalog=self.dir, key="sql")
        insert_supplier_sku_relation = public_data.public_value('insert_supplier_sku_relation')
        try:
            conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db)
            cur = conn.cursor()
            cur.execute(insert_supplier_sku_relation)
            print("供货关系表（supplier_sku_relation）插入数据成功")
        except:
            self.singular = str(traceback.format_exc())
            outcome('red', self.singular)
            return self.singular
        finally:
            cur.close()
            conn.commit()
            conn.close()

    # def insert_sku_purchaser_reserve_days_relation(self):
    #     """向sku与采购员 备货天数关系表插入数据"""
    #     public_data = ReadPublic(catalog=self.dir, key="sql")
    #     insert_sku_purchaser_reserve_days_relation = public_data.public_value('insert_sku_purchaser_reserve_days_relation')
    #     try:
    #         conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db)
    #         cur = conn.cursor()
    #         cur.execute(insert_sku_purchaser_reserve_days_relation)
    #         print("采购员 备货天数关系表（sku_purchaser_reserve_days_relation）插入数据成功")
    #     except:
    #         self.singular = str(traceback.format_exc())
    #         outcome('red', self.singular)
    #         return self.singular
    #     finally:
    #         cur.close()
    #         conn.commit()
    #         conn.close()

    def insert_sku_intransit(self):
        """向在途表插入数据"""
        public_data = ReadPublic(catalog=self.dir, key="sql")
        insert_sku_intransit = public_data.public_value('insert_sku_intransit')
        try:
            conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db)
            cur = conn.cursor()
            cur.execute(insert_sku_intransit)
            print("在途表（sku_intransit）插入数据成功")
        except:
            self.singular = str(traceback.format_exc())
            outcome('red', self.singular)
            return self.singular
        finally:
            cur.close()
            conn.commit()
            conn.close()

    def update_order(self):
        """修改订单表时间"""
        create_t = get_data(-1) + " 00:00:00"
        create_d = get_data(0)
        public_data = ReadPublic(catalog=self.dir, key="sql")
        update_order = public_data.public_value('update_order').format(create_t, create_d)
        try:
            conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db)
            cur = conn.cursor()
            cur.execute(update_order)
            print("订单表（order）修改时间成功")
        except:
            self.singular = str(traceback.format_exc())
            outcome('red', self.singular)
            return self.singular
        finally:
            cur.close()
            conn.commit()
            conn.close()


    def review_query(self, **kwargs):
        """ 待检核工作台列表 """
        readkw = self.key_world
        public_data = ReadPublic(catalog=self.dir, key="review_query")
        url = self.base_url + public_data.public_value("url")
        data = public_data.public_value("bar")
        data['warehouseId'] = ConfigYaml("warehouseId").base_config
        # data['purchaseSaleStatus'] = readkw.key_world_value("purchaseSaleStatus")
        data.update(kwargs)
        data['pageIndex'] = readkw.key_world_value("pageIndex")
        data['pageSize'] = readkw.key_world_value("pageSize")
        r = requests.get(url, headers=self.headers, params=data, stream=True, verify=False)
        res = r.json()
        if len(res['data']['list']) > 0:
            return r, url, data
        else:
            """执行定时任务同步数据至检核工作台"""



if __name__ == "__main__":
    BacklogData().job_to_review()
    # BacklogData().insert_order()
    # BacklogData().update_order()